<template>
  <div class="dashboard-container"
       v-loading="loading">
    <el-row class="header-nav">
      <el-col class="header-nav-left"
              :span="12">
        <img src="static/img/newLogo.png" />
        <!-- <div class="newLogo"></div> -->
      </el-col>
      <el-col class="header-nav-right"
              :span="12">
        <span>Welcome YICT</span>
      </el-col>
    </el-row>
    <!-- <div class="dashboard-text">name:{{name}}</div> -->
    <!-- <div class="dashboard-text">roles:<span v-for='role in roles' :key='role'>{{role}}</span></div> -->
    <!-- <appConfig ref="appConfigForm" @flushAppConfig="flushAppConfig" /> -->

    <el-row v-if="bingTem">
      <el-col :span="8"
              style="padding: 20px">
        <el-card :body-style="{ padding: '0px' }">
          <!-- <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image"> -->
          <div style="padding: 14px;">
            <span>智能终端入匝</span>
            <div class="bottom clearfix">
              <el-button style="float: right"
                         @click="toPage('CMSAutoCreate')"
                         type="text"
                         class="button">GO TO</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8"
              style="padding: 20px">
        <el-card :body-style="{ padding: '0px' }">
          <!-- <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image"> -->
          <div style="padding: 14px;">
            <span>智能终端</span>
            <div class="bottom clearfix">
              <el-button style="float: right"
                         @click="toPage('CMSAuto')"
                         type="text"
                         class="button">GO TO</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8"
              style="padding: 20px">
        <el-card :body-style="{ padding: '0px' }">
          <!-- <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image"> -->
          <div style="padding: 14px;">
            <span>GateOutAuto</span>
            <div class="bottom clearfix">
              <el-button style="float: right"
                         @click="toPage('GateOutAuto')"
                         type="text"
                         class="button">GO TO</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row v-if="bingTem">
      <el-col :span="8"
              style="padding: 20px">
        <el-card :body-style="{ padding: '0px' }">
          <!-- <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image"> -->
          <div style="padding: 14px;">
            <span>CMSManualOSD</span>
            <div class="bottom clearfix">
              <el-button style="float: right"
                         @click="toPage('CMSManualOSD')"
                         type="text"
                         class="button">GO TO</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8"
              style="padding: 20px">
        <el-card :body-style="{ padding: '0px' }">
          <!-- <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image"> -->
          <div style="padding: 14px;">
            <span>CMSManualSSD</span>
            <div class="bottom clearfix">
              <el-button style="float: right"
                         @click="toPage('CMSManualSSD')"
                         type="text"
                         class="button">GO TO</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8"
              style="padding: 20px">
        <el-card :body-style="{ padding: '0px' }">
          <!-- <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image"> -->
          <div style="padding: 14px;">
            <span>GateOutManual</span>
            <div class="bottom clearfix">
              <el-button style="float: right"
                         @click="toPage('GateOutManual')"
                         type="text"
                         class="button">GO TO</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row v-if="bingTem">
      <el-col :span="8"
              style="padding: 20px">
        <el-card :body-style="{ padding: '0px' }">
          <!-- <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image"> -->
          <div style="padding: 14px;">
            <span>WeightingAuto</span>
            <div class="bottom clearfix">
              <el-button style="float: right"
                         @click="toPage('WeightingAuto')"
                         type="text"
                         class="button">GO TO</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8"
              style="padding: 20px">
        <el-card :body-style="{ padding: '0px' }">
          <!-- <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image"> -->
          <div style="padding: 14px;">
            <span>ToGps</span>
            <div class="bottom clearfix">
              <el-button style="float: right"
                         @click="toPage('ToTGPS')"
                         type="text"
                         class="button">GO TO</el-button>
            </div>
          </div>
        </el-card>
      </el-col>

    </el-row>

    <div v-if="!bingTem"
         style="text-align: center; padding: 20px; height: 100%">
      <img class="loginImg"
           src="static/img/login2.png" />
      <div class="errText"
           style="text-align: center">
        <h3>
          {{errorMsg}}
        </h3>
      </div>
    </div>

    <!-- <el-row>
        <el-col span="8" style="padding: 20px">
         <el-card :body-style="{ padding: '0px' }">
            <div style="padding: 14px;">
              <span>CMSOutAuto</span>  
              <div class="bottom clearfix"> 
                <el-button style="float: right" @click="toPage('CMSOutAuto')" type="text" class="button">GO TO</el-button>
              </div>
            </div> 
          </el-card>
       </el-col>
     </el-row> -->

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { ipcRenderer } from 'electron'
import appConfig from '@/views/system/app-config'
import axios from 'axios'

import {
  showSuccessMsg,
  showErrorMsg,
  showWarningMsg,
  showInfoMsg,
  showNotify,
  debugLog,
  log
} from '@/utils/message'

import { getRouter } from '@/utils/router-map'
import { getNetworkIp } from '@/utils/http'
import { clearTimeout } from 'timers'


export default {
  name: 'dashboard',
  components: {
    appConfig,
  },
  computed: {
    ...mapGetters(['name', 'roles']),
  },
  data () {
    return {
      loading: false,
      bingTem: true,
      errorMsg: '',
      reloadCount: 0,
      sendMqttMsgSeq: 0,
      isReload: false,
      heart: null,
      appConfigData: null,
    }
  },
  created () {
    // console.log(__dirname) s
    // let t = Date.now() + ''
    // console.log(parseInt(t.substring(t.length - 10)))

    this.heart = setInterval(() => {
      log('开始检查连接')
      ipcRenderer.send('send-mqtt-client-check')
    }, 60000)


    ipcRenderer.on('send-mqtt-client-check-reply', (event, res) => {
      if (res === 200) {
        log('客服端正常, 心跳正常.')
      } else {
        log('检测到客户端未连接， 执行重连')
        this.reConnection()
      }
    })

    this.readAppConfigInfo()
    // console.log('core.indexCMSManualOSD', getRouter('CMSOutAuto'))
    // this.$router.push(getRouter('GateOutAuto')) 
    //TODO 在这里进行集成设备平台注册，注册成功进行切换
  },
  methods: {
    toPage (url) {
      if (this.heart) {
        clearInterval(this.heart)
      }

      console.log('core.indexto page url', url)
      ipcRenderer.removeAllListeners()
      this.$router.push(getRouter(url.trim()))
    },
    // 读取配置文件
    readAppConfigInfo () {
      // this.loading = true
      log('core.index==============读取本地文件的配置文件================')
      //读取文件信息
      ipcRenderer.send('read-app-config', '读取本地文件的配置文件')

      //接受读取到的信息
      ipcRenderer.on('read-app-config-reply', (event, res) => {
        log('core.index====read-app-config-reply index====')
        debugLog(res)
        if (res.success) {
          // 判断配置信息是否有效
          if (this.validAppConfig(res)) {
            var appConfigInfo = JSON.parse(res.data)
            this.appConfigData = appConfigInfo

            // 临时测试代码
            this.$store.commit('SET_APP_CONFIG', appConfigInfo)
            log("成功读取到appconfig", appConfigInfo)
            this.deviceAuthenticate(appConfigInfo)


          }
        } else {
          showErrorMsg(res)
        }
      })
    },
    // 验证配置文件有效性
    validAppConfig (appConfigInfo) {
      if (
        appConfigInfo === 'null' ||
        appConfigInfo.data === '' ||
        !JSON.parse(appConfigInfo.data).deviceSerialNo ||
        !JSON.parse(appConfigInfo.data).eipUrl ||
        JSON.parse(appConfigInfo.data).deviceSerialNo === '' ||
        JSON.parse(appConfigInfo.data).eipUrl === ''
      ) {
        this.showAppConfigForm()
        return false
      }
      return true
    },
    // 弹出配置信息表单
    showAppConfigForm () {
      // log('core.index==============弹出填写窗口================')
      // this.$refs.appConfigForm.show()
    },
    // 刷新保存配置数据
    flushAppConfig (configObject) {
      log('core.index=====配置表单来的数据====')
      debugLog(configObject)
      this.deviceAuthenticate(configObject)
    },
    reloadDeviceAuthenticate (queryObject, icount) {
      setTimeout(() => {
        if (icount == undefined) {
          icount = 0;
        }
        this.deviceAuthenticate(queryObject, icount++)
      }, 10000)
    },
    // 设备注册操作
    deviceAuthenticate (queryObject, icount) {
      debugLog('core.index===发起设备认证注册===')
      debugLog(queryObject, '设备注册')
      axios
        .post(queryObject.eipUrl + '/api/deviceAuthenticate', queryObject, {
          timeout: 3000,
        })
        .then((res) => {
          var ret = res.data
          if (ret.result && ret.result === 'success') {
            log('core.index===设备注册成功===')
            // 拿到MQTT地址 保存到本地
            queryObject.sessionId = ret.data.sessionId
            queryObject.serviceInstanceIpAddress =
              ret.data.serviceInstanceIpAddress
            queryObject.serviceInstanceMqttPort =
              ret.data.serviceInstanceMqttPort
            //将必要注册信息保存 主要保存MQTT的地址和端口
            this.appConfigData = queryObject

            this.$store.commit('SET_APP_CONFIG', queryObject)
            //TODO 这里应该根据注册信息获取
            console.log('开始初始化读卡串口')
            ipcRenderer.send('init-com', this.appConfigData.readIcPort, this.$store.getters.terminalDtl.iccardType)

            // 启动MQTT
            debugLog(this.appConfigData, ' this.appConfigData')
            this.connectMqtt(queryObject)
          } else {
            this.$message({
              message: '设备注册异常, 正在重连',
              duration: 10000,
              type: 'error'
            })

            // this.reloadDeviceAuthenticate(this.appConfigData, icount)
          }
        })
        .catch((error) => {
          debugLog(error)
          // this.showMsg('系统超时', 'error')
        })
    },
    // MQTT 连接
    connectMqtt (mqttObject) {
      debugLog('core.indexstartMqttConnect')
      debugLog(mqttObject, 'MQTT连接信息')
      ipcRenderer.send('start-mqtt-connect', mqttObject)

      ipcRenderer.on('start-mqtt-connect-reply', (event, res) => {
        log('core.index====start-mqtt-connect-reply index====', res)
        // 关闭重连标识
        this.isReload = false
        if (res) {
          // debugLog(res, 'MQTT连接返回结果')
          this.getClientType()
        }
      })

      // ipcRenderer.on("UpdateMsg", (event, age) => {
      //   switch (age.state) {
      //     case -2:
      //       console.log(age.msg)
      //       break
      //     case -1:
      //       console.log('core.index自动更新程序更新发生了错误， 访问的Http接口为：', this.$store.getters.config.updateUrls)
      //       break;
      //     case 0:
      //       console.log('core.index自动更新程序正在检查更新， 访问的Http接口为：', this.$store.getters.config.updateUrl)
      //       break;
      //     case 1:
      //       console.log('core.index已检查到新版本，开始下载')
      //       break;
      //     case 2:
      //       console.log('core.index无新版本')
      //       break;
      //     case 3:
      //       break;
      //     case 4:
      //       console.log('core.index更新下载完成！')
      //       break;

      //     default:
      //       break;
      //   }
      // });

      //注册业务返回监听器
      ipcRenderer.on('send-mqtt-client-message-reply', (event, res) => {
        log('core.index===send-mqtt-client-message-reply index===')
        if ('客户端未连接' === res) { }
        debugLog(res)
      })
      ipcRenderer.on('mqtt-server-message-topic', (event, res) => {
        log('core.index===mqtt-server-message-topic index===')
        this.handleMqttMessage(res)
      })

      ipcRenderer.on('mqtt-heart-send', (event, res) => {
        log('core.index==发包===', res)

        if (res.cmd.indexOf('connect') > -1) {
          // this.showMsg('服务器正在重连', 'error')
          showErrorMsg('服务不可用，服务正在重连', 'error')
          log('core.index服务不可用，服务正在重连')
        }
      })

      ipcRenderer.on('mqtt-heart-receive', (event, res) => {
        log('core.index==收包===', res.cmd)
      })
    },
    // 重连MQTT
    reConnection () {
      // showErrorMsg('服务不可用，请稍后重试或联系服务台处理', 'error')
      log('core.index正在重连')
      this.closeMqttConnect()
      this.deviceAuthenticate(this.appConfigData)
    },
    // 关闭 MQTT服务器
    closeMqttConnect () {
      log('core.layoutcloseMqttConnect')
      ipcRenderer.send('close-mqtt-connect')
    },
    // MQTT后端业务返回消息处理方法
    handleMqttMessage (mqttMessage) {
      //{"sn":"NGSA000001","id":1234567,"ic":"AutoCreate","en":false,"rc":1,"dt":["192764","zxc","","y|GD|BW8337|",""]}
      console.log('core.indexhandleMqttMessage index---->', mqttMessage)
      debugLog('core.index------ handleMqttMessage', JSON.stringify(mqttMessage))
      log('core.index------ handleMqttMessage', JSON.stringify(mqttMessage))
      if (!mqttMessage) {
        console.error('handleMqttMessage ----> 异常， 没有返回值')
        return
      }

      var messageObject = JSON.parse(mqttMessage)
      debugLog(messageObject, '回传信息')
      if (messageObject.rc && messageObject.rc === 1) {
        if (messageObject.ic === 'GetClientType') {
          // 跳转页面
          if (!messageObject.dt || !messageObject.dt.clientType) {
            showErrorMsg('未绑定终端')
            this.bingTem = false
            this.errorMsg = messageObject.rm
            return
          }

          // 回写用户信息 
          this.$store.commit('SET_TERMINAL', messageObject.dt)
          this.toPage(messageObject.dt.clientType)
        }
      } else if (messageObject.rc) {
        //{"sn":"NGSA000001","id":1234567,"ic":"AutoCreate","en":false,"rc":26,"rm":"未知的读卡器错误"}
        console.log(messageObject.rm, 'blue')
        if (messageObject.ic === 'GetClientType') {
          showErrorMsg(messageObject.rm)
        }
      } else {
        console.log('core.index未知错误，请联系管理员。')
      }
    },
    getClientType () {
      log('core.index===获取设备类型MQTT===')
      console.log('core.index===获取设备类型MQTT===')
      debugLog(this.appConfigData)
      this.sendMqttMsgSeq += 1
      let message = {
        dt: {
          ip: getNetworkIp(),
        },
        ic: 'GetClientType',
        sn: this.appConfigData.deviceSerialNo,
        id: this.sendMqttMsgSeq,
        en: false,
      }
      debugLog(JSON.stringify(message))
      ipcRenderer.send('get-client-type-message', message)
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard {
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.errText {
  padding: 10px;
  color: red;
  font-size: 30px;
}

.loginImg {
  margin-top: 70px;
}
.dashboard-container {
  padding: 0px;
  height: 100vh;
  background: url("/static/img/bg.png");
}

.header-nav {
  width: 100%;
  height: 45px;
  padding: 0 15px;
  background: linear-gradient(180deg, #f7fbff 0%, #ebf0ff 100%);
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.5), inset 0px -1px 2px 0px #b0b9ce;
}
.header-nav > .header-nav-left {
  cursor: pointer;
}
.header-nav > .header-nav-left > img {
  height: 35px;
  margin-top: 5px;
}
.header-nav > .header-nav-right {
  height: 100%;
  padding-top: 7.5px;
  /* display:flex; */
  text-align: right;
  align-items: center;
}
.header-nav > .header-nav-right > span {
  font-size: 17px;
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-weight: bold;
  color: #213767;
  line-height: 26px;
  text-shadow: 0px 1px 0px rgba(255, 255, 255, 0.5);
}
</style>
